using System;
using System.Collections;
using System.Text;

// string encoding complete

namespace csammisrun.OscarLib.Utility
{
	/// <summary>
	/// Provides static methods for processing messages in SNAC family 0x000A -- User lookup service
	/// </summary>
	internal static class SNAC0A
	{
    /// <summary>
		/// Sends a request to find accounts by their associated email address -- SNAC(0A,02)
		/// </summary>
		/// <param name="sess">A <see cref="Session"/> object</param>
		/// <param name="email">The email address to query</param>
		public static void FindUsersByEmail(Session sess, string email)
		{
			SNACHeader sh = new SNACHeader();
			sh.FamilyServiceID = (ushort)SNACFamily.UserLookupService;
			sh.FamilySubtypeID = (ushort)UserLookupService.FindUserByEmailRequest;
			sh.Flags = 0x0000;
			sh.RequestID = sess.GetNextRequestID();

      Encoding enc = Marshal.ASCII;
      int emaillength = enc.GetByteCount(email);

			int index = 0;
			byte[] buffer = new byte[emaillength];
      Marshal.InsertString(buffer, email, enc, ref index);

			sess.StoreRequestID(sh.RequestID, email);

			DataPacket dp = Marshal.BuildDataPacket(sess, sh, buffer);
			SNACFunctions.BuildFLAP(dp);
		}

		/// <summary>
		/// Processes the results of a search-by-email request -- SNAC(0A,03)
		/// </summary>
		/// <param name="dp">A <see cref="DataPacket"/> object with a buffer containing SNAC(0A,03)</param>
		public static void ProcessSearchResults(DataPacket dp)
		{
			byte[] SNACData = dp.Data;

			int index = 0;
			ushort key, keylength;
			string email = (string)dp.ParentSession.RetrieveRequestID(dp.SNAC.RequestID);
			ArrayList accts = new ArrayList();
      Encoding enc = Marshal.ASCII;

			while(index < SNACData.Length)
			{
				key = Marshal.ByteArrayToUshort(SNACData, ref index);
				keylength = Marshal.ByteArrayToUshort(SNACData, ref index);
				switch(key)
				{
					case 0x0001:
						string tmp = Marshal.ByteArrayToString(SNACData, ref index, keylength, enc);
						accts.Add(tmp);
						break;
					default:
						index += keylength;
						break;
				}
			}

			string[] accounts = new string[accts.Count];
			for(int i = 0; i < accts.Count; i++)
				accounts[i] = (string)accts[i];

			dp.ParentSession.OnSearchByEmailResults(email, accounts);
		}
	}
}
